package com.gap.employee;

import com.buanalintas.framework.Action;
import com.buanalintas.framework.Controller;
import com.buanalintas.framework.Dictionary;
import com.gap.entities.GapTransactionEmployee;
import com.buanalintas.framework.Field;
import com.buanalintas.framework.Logger;
import com.buanalintas.framework.Page;
import com.buanalintas.framework.Persistence;
import com.buanalintas.framework.Sequence;
import com.buanalintas.framework.Utility;
import com.buanalintas.framework.formatter.DateFormatter;
import com.gap.entities.GapMasterEmployee;
import com.gap.entities.GapMasterHistoryEmployee;
import com.gap.entities.GapTransactionHistoryEmployee;
import com.gap.entities.GapTransactionRevision;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * Class Employee is ...
 *
 * Generated on Fri Jan 09 13:17:48 ICT 2015
 *
 * @version 1.0
 * @author Mr. Kazao™
 * @since Bynga 1.0
 *
 */
public class TransactionEmployee extends Page {

    private Field posId;

    private Field posEmployeeName;

    private Field posDate;

    private Field posNumber;

    private Field posPlatform;
    
    private Field posItem;
    
    private Field posItemPrice;
    
    private Field posDiscountNominal;

    private Field posValue;

    private Field posCurrent;

    private Field posLast;

    private Field posTimestamp;

    private Field posUserId;

    private Field posUnitId;

    private Field posEmployeeId;

    private Field posDescription;

    public TransactionEmployee() {
        super();

        setTheClass(GapTransactionEmployee.class);

        posId = new Field();
        posId.setName("posId");
        posId.setCaption("id");
        //posId.setInfo("pos id");
        posId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        posId.setInputProperties(" size=\"20\"");
        getFields().add(posId);

        posEmployeeName = new Field();
        posEmployeeName.setName("posEmployeeName");
        posEmployeeName.setCaption("employee name");
        posEmployeeName.setRequired(true);
        posEmployeeName.setListProperties(" align=\"left\" width=\"20%\" nowrap");
        posEmployeeName.setInputProperties(" size=\"50\"");
        getFields().add(posEmployeeName);

        posDate = new Field();
        posDate.setName("posDate");
        posDate.setCaption(" date");
        posDate.setRequired(true);
        posDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        posDate.setInputProperties(" size=\"8\"");
        posDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(posDate);

        posNumber = new Field();
        posNumber.setName("posNumber");
        posNumber.setCaption("number");
        posNumber.setRequired(true);
        posNumber.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        posNumber.setInputProperties(" size=\"20\" readonly");
        getFields().add(posNumber);

        posPlatform = new Field();
        posPlatform.setName("posPlatform");
        posPlatform.setCaption("platform");
        posPlatform.setRequired(true);
        posPlatform.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        posPlatform.setInputProperties(" size=\"20\"");
        getFields().add(posPlatform);
        
        posItem = new Field();
        posItem.setName("posItem");
        posItem.setCaption("item");
        posItem.setRequired(true);
        posItem.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        posItem.setInputProperties(" size=\"30\" ");
        getFields().add(posItem);

        posItemPrice = new Field();
        posItemPrice.setName("posItemPrice");
        posItemPrice.setCaption("price");
        posItemPrice.setRequired(true);
        posItemPrice.setDefaultValue(0);
        posItemPrice.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        posItemPrice.setInputProperties(" size=\"20\"");
        getFields().add(posItemPrice);
        
        posDiscountNominal = new Field();
        posDiscountNominal.setName("posDiscountNominal");
        posDiscountNominal.setCaption("discount");
        posDiscountNominal.setRequired(true);
        posDiscountNominal.setDefaultValue(0);
        posDiscountNominal.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        posDiscountNominal.setInputProperties(" size=\"20\"");
        getFields().add(posDiscountNominal);

        posValue = new Field();
        posValue.setName("posValue");
        posValue.setCaption("value");
        posValue.setRequired(true);
        posValue.setDefaultValue(0);
        posValue.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        posValue.setInputProperties(" size=\"20\"");
        getFields().add(posValue);

        posCurrent = new Field();
        posCurrent.setName("posCurrent");
        posCurrent.setCaption("saldo");
        posCurrent.setRequired(true);
        posCurrent.setDefaultValue(0);
        posCurrent.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        posCurrent.setInputProperties(" size=\"20\"");
        getFields().add(posCurrent);

        posLast = new Field();
        posLast.setName("posLast");
        posLast.setCaption("last");
        posLast.setRequired(true);
        posLast.setDefaultValue(0);
        posLast.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        posLast.setInputProperties(" size=\"20\"");
        getFields().add(posLast);

        posTimestamp = new Field();
        posTimestamp.setName("posTimestamp");
        posTimestamp.setCaption("timestamp");
        //posTimestamp.setInfo("pos timestamp");
        posTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        posTimestamp.setInputProperties(" size=\"12\"");
        //posTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(posTimestamp);

        posUserId = new Field();
        posUserId.setName("posUserId");
        posUserId.setCaption("user");
        //posUserId.setInfo("pos user id");
        posUserId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        posUserId.setInputProperties(" size=\"20\"");
        getFields().add(posUserId);

        posUnitId = new Field();
        posUnitId.setName("posUnitId");
        posUnitId.setCaption("unit");
        //posUnitId.setInfo("pos unit id");
        posUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        posUnitId.setInputProperties(" size=\"20\"");
        getFields().add(posUnitId);

        posEmployeeId = new Field();
        posEmployeeId.setName("posEmployeeId");
        posEmployeeId.setCaption("employee");
        posEmployeeId.setRequired(true);
//        posEmployeeId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        posEmployeeId.setInputProperties(" size=\"30\"");
        posEmployeeId.setSelectorOrder("t.employeeNumber");
        posEmployeeId.getSelectorAction().add(new String[]{"value", "posEmployeeName", "employeeNameFirst"});
        posEmployeeId.getSelectorAction().add(new String[]{"value", "posPlatform", "employeePlatform"});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeeNumber", "ID", "width=\"20%\" nowrap"});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeeNameFirst", "Name", "width=\"50%\""});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeePlatform", "Platform", "width=\"20%\" nowrap"});
        getFields().add(posEmployeeId);

        posDescription = new Field();
        posDescription.setName("posDescription");
        posDescription.setCaption(" description");
        //revisionDescription.setInfo("revision description");
        posDescription.setListProperties(" width=\"20%\"");
        posDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        posDescription.setInputType(Field.INPUT_TEXT_AREA);
        getFields().add(posDescription);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);
        fillFields();
        getFieldsAdd().clear();
        getFieldsAdd().clear();
        getFieldsAdd().add(posDate);
        getFieldsAdd().add(posNumber);
        getFieldsAdd().add(posEmployeeId);
        getFieldsAdd().add(posEmployeeName);
        getFieldsAdd().add(posPlatform);
        getFieldsAdd().add(posItem);
        getFieldsAdd().add(posItemPrice);
        getFieldsAdd().add(posDiscountNominal);
        getFieldsAdd().add(posValue);
        getFieldsAdd().add(posDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(posDate);
        getFieldsEdit().add(posNumber);
        getFieldsEdit().add(posEmployeeId);
        getFieldsEdit().add(posEmployeeName);
        getFieldsEdit().add(posPlatform);
        getFieldsEdit().add(posItem);
        getFieldsEdit().add(posItemPrice);
        getFieldsEdit().add(posDiscountNominal);
        getFieldsEdit().add(posValue);
        getFieldsEdit().add(posDescription);

        getFieldsList().clear();
        getFieldsList().add(posDate);
        getFieldsList().add(posNumber);
        getFieldsList().add(posEmployeeId);
        getFieldsList().add(posEmployeeName);
        getFieldsList().add(posPlatform);
        getFieldsList().add(posItem);
        getFieldsList().add(posItemPrice);
        getFieldsList().add(posDiscountNominal);
        getFieldsList().add(posLast);
        getFieldsList().add(posValue);
        getFieldsList().add(posCurrent);
        getFieldsList().add(posDescription);

        getFieldsView().clear();
        getFieldsView().add(posDate);
        getFieldsView().add(posNumber);
        getFieldsView().add(posEmployeeId);
        getFieldsView().add(posEmployeeName);
        getFieldsView().add(posPlatform);
        getFieldsView().add(posItem);
        getFieldsView().add(posItemPrice);
        getFieldsView().add(posDiscountNominal);
        getFieldsView().add(posLast);
        getFieldsView().add(posValue);
        getFieldsView().add(posCurrent);
        getFieldsView().add(posDescription);
        getFieldsView().add(posUserId);
        getFieldsView().add(posUnitId);
        getFieldsView().add(posTimestamp);

        setController(new TransactionEmployeeController(this));
        setExportList(getClass().getResourceAsStream("TransEmployeeList.jasper"));
        setExport(getClass().getResourceAsStream("TransEmployee.jasper"));
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        posDate.setFormatter(DateFormatter.getInstanceDate(this));
        posTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));

    }

//    @Override
//    public String validate(Object data) {
//        HttpSession session = getRequest().getSession();
//        EntityManager em = getEntityManager();
//        GapTransactionEmployee employ = (GapTransactionEmployee) data;
//        BigDecimal ini =  employ.getPosValue();
//        if (ini.compareTo(employ.getPosCurrent()) > 0) {
//            return Dictionary.getValue(this, "Saldo bulan ini sebesar" + employ.getPosCurrent()
//                    + " , nilai transaksi anda " + employ.getPosValue());
//        }
//
//        return null;
//    }
    @Override
    public void beforeAdd() {
        posNumber.setDefaultValue(generate());
    }

    class TransactionEmployeeController extends Controller {

        public TransactionEmployeeController(Page page) {
            super(page);
            setOrder(posTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data) {
            EntityManager em = getEntityManager();
            GapTransactionEmployee employee = (GapTransactionEmployee) data;
            employee.setPosNumber(generate());
            employee.setPosUnitId(getCurrentUnit());
            employee.setPosUserId(getCurrentUser());
            employee.setPosTimestamp(Utility.getTimestamp());

            GapMasterHistoryEmployee masterhis = Employee.getStock(em, employee.getPosEmployeeId());
            GapTransactionHistoryEmployee history = new GapTransactionHistoryEmployee();

            employee.setPosLast(masterhis.getHistoryValue());

            BigDecimal Saldo = BigDecimal.ZERO;
            
            //-----ITEM------
            BigDecimal harga = BigDecimal.ZERO;
            harga = employee.getPosItemPrice().subtract(employee.getPosDiscountNominal());
            System.out.println("hargaaaaa :"+harga);
            //---------------
            
            GapMasterEmployee mase = null;
            try {
                mase = (GapMasterEmployee) em.createQuery("SELECT t FROM GapMasterEmployee t WHERE t.employeeId='" + employee.getPosEmployeeId().getEmployeeId() + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                 System.out.println("mase jose ---->" + mase);
            } catch (Exception e) {
                Logger.log(e);
                System.out.println("eeeeee :"+e);
            }

            if (mase.getEmployeeStatusBonus() == "2") {
                Saldo = (employee.getPosPlatform().subtract(employee.getPosLast()))
                        .subtract(harga)
                        .subtract(employee.getPosValue());
                System.out.println("Saldo 2 ---->" + Saldo);
                
                employee.setPosCurrent(Saldo);
            }
//                if (employee.getPosEmployeeId().getEmployeeStatusBonus() == "1") {
            Date date = employee.getPosDate();
//            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            int month = cal.get(Calendar.MONTH) + 1;
            System.out.println("MONTH ---->" + month);

            int beb = 0;

            if (month > 6) {
                beb = month - 6;
                System.out.println("beb 1---->" + beb);
            } else {
                beb = 6 + month;
                System.out.println("beb 2---->" + beb);
            }

            BigDecimal b = new BigDecimal(beb);
            BigDecimal bln = new BigDecimal(12);
            System.out.println("bln ---->" + bln);

            Saldo = ((employee.getPosPlatform().divide(bln).multiply(b))
                    .subtract(employee.getPosLast()))
                    .subtract(harga)
                    .subtract(employee.getPosValue());
            System.out.println("Saldo 1 ---->" + Saldo);
            employee.setPosCurrent(Saldo);

        }

        @Override
        public void afterInsert(Object data) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            GapTransactionEmployee e = (GapTransactionEmployee) data;
            System.out.println("jose 1---->" + e);
            GapMasterHistoryEmployee masterhis = Employee.getStock(em, e.getPosEmployeeId());
            GapTransactionHistoryEmployee history = new GapTransactionHistoryEmployee();

            history.setHistoryId(Sequence.uuid());
            history.setHistoryEmployeeId(e.getPosEmployeeId());
            history.setHistoryUnitId(getCurrentUnit());
            history.setHistoryUserId(getCurrentUser());
            history.setHistoryDate(e.getPosDate());
            history.setHistoryEmployeeName(e.getPosEmployeeName());
            history.setHistoryPlatform(e.getPosPlatform());
            history.setHistoryLast(masterhis.getHistoryValue());
            history.setHistoryCurrent(e.getPosCurrent());
            history.setHistoryValue(e.getPosValue());
            history.setHistoryDescription(e.getPosDescription());
            history.setHistoryTimestamp(e.getPosTimestamp());
            em.persist(history);
            masterhis.setHistoryValue(history.getHistoryCurrent());
            System.out.println("Curreennnttt ---->" + history.getHistoryCurrent()+ " master his :"+masterhis.getHistoryValue());
            masterhis.setHistoryTimestamp(history.getHistoryTimestamp());
            masterhis.setHistoryUnitId(history.getHistoryUnitId());
            masterhis.setHistoryEmployeeId(history.getHistoryEmployeeId());
            masterhis.setHistoryEmployeeName(history.getHistoryEmployeeName());
            masterhis.setHistoryPlatform(history.getHistoryPlatform());
            
            
//            //--------REVISION-----------
//            GapTransactionRevision rev = new GapTransactionRevision();
//            rev.setRevisionId(Sequence.uuid());
//            rev.setRevisionPosId(e);
//            rev.setRevisionNumber(e.getPosNumber());
//            rev.setRevisionItem(e.getPosItem());
//            rev.setRevisionItemPrice(e.getPosItemPrice());
//            rev.setRevisionDiscountNominal(e.getPosDiscountNominal());
//            rev.setRevisionEmployeeId(e.getPosEmployeeId());
//            rev.setRevisionLast(rev.getRevisionLast());
//            rev.s

            em.getTransaction().commit();
        }
    }

    public String generate() {
        String unitCode = getCurrentUnit().getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            GapTransactionEmployee employee = (GapTransactionEmployee) getEntityManager().createQuery("SELECT t FROM GapTransactionEmployee t WHERE t.posNumber LIKE '%/" + unitCode + "/GAP/%/" + year + "' ORDER BY t.posTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(employee.getPosNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/GAP/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/GAP/" + month + "/" + year;
    }
    
     @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Transaction Employee"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
